<template>
  <GenericImportWizard
    v-model="visible"
    title="导入供应商"
    :field-mapping-config="fieldConfig"
    :import-instructions="importInstructions"
    template-file-name="供应商导入模板.csv"
    :import-function="importSuppliersFunction"
    @import-success="handleImportSuccess"
    @file-selected="handleFileSelected"
    @field-mapped="handleFieldMapped"
  />
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import GenericImportWizard from '@/components/import-wizard/GenericImportWizard.vue'
import * as procurementAPI from '@/api/procurement'

const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'import-success'): void
}>()

const visible = computed({
  get: () => {
    console.log('SupplierImportWizard visible get:', props.modelValue);
    return props.modelValue;
  },
  set: (val: boolean) => {
    console.log('SupplierImportWizard visible set:', val);
    emit('update:modelValue', val);
  }
})

// 字段配置
const fieldConfig = [
  { key: 'name', label: '供应商名称', width: 120 },
  { key: 'contactPerson', label: '联系人' },
  { key: 'phone', label: '联系电话' },
  { key: 'email', label: '邮箱' }
]

// 导入说明
const importInstructions = [
  '支持Excel和CSV格式的供应商数据文件',
  '文件大小不超过10MB',
  '建议包含供应商名称、联系人、电话等基本信息',
  '系统将自动检测文件中的列名'
]

// 供应商导入函数
const importSuppliersFunction = async (file: File, mapping: Record<string, string>) => {
  // 显示处理中提示
  ElMessage.info('正在导入供应商数据，请稍候...');
  
  // 调用后端API进行导入，传递文件对象和字段映射
  try {
    const result = await procurementAPI.importSuppliers(file, mapping);
    if (result.success) {
      ElMessage.success('供应商导入成功');
      return result.data;
    } else {
      ElMessage.error('导入失败: ' + (result.message || '未知错误'));
      throw new Error(result.message);
    }
  } catch (error: any) {
    // 显示具体的错误信息
    if (error.message) {
      ElMessage.error('导入失败: ' + error.message);
    } else {
      ElMessage.error('导入失败，请重试');
    }
    throw error;
  }
}

// 处理导入成功
const handleImportSuccess = () => {
  ElMessage.success('供应商导入成功')
  emit('import-success')
}

// 处理文件选择
const handleFileSelected = (file: File) => {
  console.log('Selected file:', file.name)
}

// 处理字段映射
const handleFieldMapped = (mapping: Record<string, string>) => {
  console.log('Field mapping:', mapping)
}
</script>

<style scoped>
.step-content {
  padding: 20px 0;
}

.step-pane {
  min-height: 300px;
}

.template-download {
  text-align: center;
  margin: 20px 0;
}

.import-info {
  margin-top: 20px;
  padding: 15px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.import-info h4 {
  margin-top: 0;
}

.import-info ul {
  padding-left: 20px;
}

.import-info li {
  margin-bottom: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>